<template>
  <div>
    <a-modal
      title="编辑收货地址"
      :visible="visible"
      width="800px"
      :footer="null"
      @cancel="handleCancel"
    >
      <a-form
        layout="inline"
        :form="addressForm"
        :label-col="{ span: 7 }"
        :wrapper-col="{ span: 17 }"
      >
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-item label="平台渠道" labelAlign="right">
              <a-input
                v-decorator="[
                  'channel',
                  {
                    rules: [{ required: true, message: 'Please input' }],
                  },
                ]"
                placeholder="Please input"
              >
                <!-- <a-select-option value="2">平台渠道</a-select-option>
                <a-select-option value="3">物流渠道</a-select-option> -->
              </a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="物流渠道" labelAlign="right">
              <a-select
                class="input-file"
                v-decorator="[
                  'shipMethod',
                  {
                    rules: [
                      {
                        required: true,
                        message: 'Please input your shipMethod!',
                      },
                    ],
                  },
                ]"
                placeholder=""
              >
                <a-select-option
                  v-for="item in shipMethodList"
                  :value="item"
                  :key="item"
                >{{ item }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="收件人" labelAlign="right">
              <a-input
                class="input-file"
                v-decorator="[
                  'receiveName',
                  {
                    rules: [
                      { required: true, message: 'Please input your name!' },
                    ],
                  },
                ]"
                placeholder=""
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="收件人手机号" labelAlign="right">
              <a-input
                class="input-file"
                v-decorator="[
                  'phone',
                  {
                    rules: [
                      { required: false, message: 'Please input your phone!' },
                    ],
                  },
                ]"
                placeholder=""
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="国家" labelAlign="right">
              <a-input
                class="input-file"
                v-decorator="[
                  'country',
                  {
                    rules: [
                      { required: true, message: 'Please input your country!' },
                    ],
                  },
                ]"
                placeholder=""
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="州" labelAlign="right">
              <a-input
                class="input-file"
                v-decorator="[
                  'state',
                  {
                    rules: [
                      { required: true, message: 'Please input your state!' },
                    ],
                  },
                ]"
                placeholder=""
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="城市" labelAlign="right">
              <a-input
                class="input-file"
                v-decorator="['city']"
                placeholder=""
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="街道" labelAlign="right">
              <a-input
                class="input-file"
                v-decorator="[
                  'street',
                  {
                    rules: [
                      { required: true, message: 'Please input your street!' },
                    ],
                  },
                ]"
                placeholder=""
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="邮编" labelAlign="right">
              <a-input
                class="input-file"
                v-decorator="[
                  'postCode',
                  {
                    rules: [
                      {
                        required: true,
                        message: 'Please input your postCode!',
                      },
                    ],
                  },
                ]"
                placeholder=""
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="详细地址" labelAlign="right">
              <a-input
                class="input-file"
                v-decorator="[
                  'address',
                  {
                    rules: [
                      {
                        required: true,
                        message: 'Please input address!',
                      },
                    ],
                  },
                ]"
                placeholder=""
              />
            </a-form-item>
          </a-col>
          
        </a-row>
      </a-form>
      <a-table style="margin-top:10px;"
        :columns="productColumn"
        :dataSource="dataSource"
        :pagination="pagination"
        :rowKey="(it) => it.id"
      >
        <template
          v-for="col in ['sysCnName', 'sysEnName']"
          :slot="col"
          slot-scope="text, record"
        >
          <div :key="col">
            <a-input
              v-if="record.editable"
              style="margin: -5px 0"
              :value="record[col]"
              @change="e => handleChangeProduct(e.target.value, record.id, col)"
            />
            <template v-else>
              {{ record[col] }}
            </template>
          </div>
        </template>
        <template slot="operation" slot-scope="text, record">
          <div class="editable-row-operations">
            <span v-if="record.editable">
              <a @click="() => saveProducts(record)" style="margin-right: 10px;">保存</a>
              <a @click="() =>cancelProduct(record.id)">取消</a>
            </span>
            <span v-else>
              <a  @click="() => editProduct(record.id)">编辑</a>
            </span>
          </div>
        </template>
      </a-table>
      <div class="btn">
        <a-button @click="handleCancel">取消</a-button>
        <a-button type="primary" :loading="btnLoading" @click="handleOk">
          确认并保存
        </a-button>
      </div>
    </a-modal>
  </div>
</template>
<script>
import {ShipLists,ProductList,SaveProduct} from '@/api/prediction'
export default {
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    btnLoading: {
      type: Boolean,
      default: false,
    },
    item: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      addressForm: this.$form.createForm(this, {
        name: "edit_address",
      }),
      shipMethodList:[],
      productColumn:[
        { title: 'SKU',width:100, align: 'center', dataIndex: 'sysSkuCode' },
        { title: '中文名',width:80, align: 'center', scopedSlots: { customRender: 'sysCnName' } },
        { title: '英文名', width:80,align: 'center', scopedSlots: { customRender: 'sysEnName' } },
        { title: '重量',width:60, align: 'center', dataIndex:'weight'},
        { title: '编辑',width:100, align: 'center', scopedSlots: {customRender: 'operation'}}
      ],
      pagination: false,
      dataSource:[],
      cacheData:[]
    };
  },
  watch: {
    visible: {
      async handler(newVal) {
        if (newVal) {
          await this.getShipList()
          await this.getProductList()
          this.$nextTick(() => {
            let {
              country = "",
              state = '',
              city = "",
              street = "",
              postCode = "",
              receiveName = "",
              channel='',
              shipMethod='',
              phone='',
              address= ''
            } = this.item;
            this.addressForm.setFieldsValue({
              country,
              state,
              city,
              street,
              postCode,
              receiveName,
              channel:channel+'',
              shipMethod,
              phone,address
            });
          });
        }
      },
      immediate: true,
    },
  },
  methods: {
    async getShipList(){
      let res = await ShipLists({channel:this.item.channel})
      this.shipMethodList = res?.data
    },
    async getProductList(){
      let res = await ProductList({orderNo:this.item.orderNo})
      this.dataSource = res?.data
      this.cacheData = res?.data.map(item => ({ ...item }));
      console.log('producttt',res)
    },
    handleChangeProduct(value, key, column) {
      const newData = [...this.dataSource];
      const target = newData.find(item => key === item.id);
      if (target) {
        target[column] = value;
        this.dataSource = newData;
      }
    },
    editProduct(key) {
      const newData = [...this.dataSource];
      const target = newData.find(item => key === item.id);
      if (target) {
        target.editable = true;
        this.dataSource = newData;
      }
    },
    async saveProducts(record) {
      const newData = [...this.dataSource];
      const target = newData.find(item => record.id === item.id);
      if (target) {
        let param = {
          id :target?.id,
          sysCnName: target?.sysCnName,
          sysEnName: target?.sysEnName
        }
        let res = await SaveProduct(param)
        console.log('rerere',res)
        if(res?.success){
          await this.getProductList()
        }else{
          this.$message.error(res?.message)
        }
      }
    },
    cancelProduct(key) {
      const newData = [...this.dataSource];
      const target = newData.find(item => key === item.id);
      if (target) {
        Object.assign(target, this.cacheData.find(item => key === item.id));
        delete target.editable;
        this.dataSource = newData;
      }
    },
    handleOk(e) {
      this.addressForm.validateFields(async(err, values) => {
        if (!err) {
          console.log('ddd',this.dataSource)
          if(this.dataSource.length>0){
            for(let i = 0;i<this.dataSource.length;i++){
              let tem = this.dataSource[i] 
              if(tem && tem.editable){
                await this.saveProducts(tem)
              } 
            }
          }
          this.$emit("ok", { ...values, id: this.item.id, orderNo: this.item.orderNo });
        }
      });
    },
    handleCancel(e) {
      this.addressForm.resetFields();
      this.$emit("close");
    },
  },
};
</script>
<style scoped lang="scss">
.ant-form-item,
.select-file,
.input-file {
  width: 100%;
}
.btn {
  padding-top: 20px;
  text-align: right;
  .ant-btn:first-child {
    margin-right: 20px;
  }
}
</style>
